// TODO: if the console is still connected and the user tries to close us, ask for confirmation.
namespace CookieTerm
{
    using System;
    using Gtk;

    public class Tab : Box
    {
        Console console;
        Label captionLabel;
        ToolButton closeButton;
        Notebook parentNotebook;

        public Tab(Bookmark bookmark, Notebook parent)
        {
			this.Name = bookmark.Name;
			this.captionLabel = new Label(bookmark.Name);
			this.CanFocus = false;

            this.parentNotebook = parent;
            this.console = new Console(bookmark, this);
			this.closeButton = new ToolButton (Image.LoadFromResource ("CookieTerm.Resources.close.png"), string.Empty);
            this.closeButton.Clicked += OnCloseButtonClicked;

            PackStart(captionLabel);
            PackStart(closeButton);

            this.console.Show();
            ShowAll();

            this.parentNotebook.CurrentPage = this.parentNotebook.AppendPage(this.console, this);
            this.console.GrabFocus();
        }

        public void OnCloseButtonClicked(object sender, EventArgs e)
        {
            string message;
            bool okayToClose = this.console.Controller.RequestToShutdown(out message);
            if (!okayToClose)
            {
                MessageDialog dialog = new MessageDialog(GetMainWindow(), DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, message);
                ResponseType response = (ResponseType)dialog.Run();
                dialog.Destroy();
                okayToClose = ResponseType.Yes == response;
            }
            if (okayToClose)
            {
                Close();
            }
        }

        public void Close()
        {
            int index = parentNotebook.PageNum(this.console);
            if (index != -1)
            {
                this.console.Close();
                parentNotebook.RemovePage(index);
            }
        }

        protected override void OnRealized()
        {
            base.OnRealized();
            this.console.OnStatusChanged += GetMainWindow().OnStatusBarTextChanged;
        }

		public MainWindow GetMainWindow()
		{
			MainWindow window = this.Parent.Parent.Parent as MainWindow;
			if (window == null) {
				throw new Exception ("Cannot obtain main window");
			}
			return window;
		}
    }
}
